package com.tegtech.tools.aws.support;

import java.util.Map;

import com.google.common.collect.Maps;
import com.tegtech.tools.aws.properties.AwsProperties;

import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;

/**
 * S3文件临时授权处理类
 * @Author Jun
 * @date 2021年2月25日 下午3:57:58
 */
public class AssumeRole {

	private static StsClient stsClient;

	static {
		if (stsClient == null) {
			stsClient = StsClient.builder()
					.region(AwsProperties.s3Region)
					.credentialsProvider(StaticCredentialsProvider.create(AwsProperties.awsBasicCredentials))
					.build();
		}
	}

	/**
	 * 获取STS临时操作权限
	 * @return
	 */
	public static Map<String, Object> stsRole() {
		Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(4);
		AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
				.roleArn(AwsProperties.getStsRoleArn())
				.roleSessionName(AwsProperties.getStsSessionName())
				.durationSeconds(3600)
				.build();

		AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
		Credentials credentials = roleResponse.credentials();

		resultMap.put("accessKeyId", credentials.accessKeyId());
		resultMap.put("secretAccessKey", credentials.secretAccessKey());
		resultMap.put("sessionToken", credentials.sessionToken());
		resultMap.put("region", AwsProperties.s3Region);
		resultMap.put("bucket", AwsProperties.getS3Bucket());
		resultMap.put("host", AwsProperties.getS3Host());
		resultMap.put("expiration", credentials.expiration().getEpochSecond());
		
		return resultMap;
	}
}
